import './App.css'
import { Suspense, lazy, useEffect } from 'react'
import router from './router'
import { RouterProvider } from 'react-router-dom'

import { RootState } from './store'
import { useSelector } from 'react-redux'

import { dynamicComponent } from './utils/dynamicComponent'
import { Menus } from './types/user'

function App () {
  const userInfo = useSelector((state: RootState) => state.user)

  useEffect(() => {
    console.log('---userInfo---', userInfo)
    if (userInfo.menus) {
      // 说明已经添加过
      if (router.routes[1].children && router.routes[1].children.length > 0)
        return
      // 没有添加过
      // const routes = {
      //   id: '1001',
      //   path: 'user/list',
      //   element: <User />
      // }

      const routeArr: { id: string; path: string; element: any }[] = []
      userInfo.menus.forEach((item: Menus) => {
        item.children.forEach(subItem => {
          const Page = lazy(dynamicComponent(subItem.component))
          console.log(Page)

          const route = {
            id: Math.random() + '',
            path: `${item.path}/${subItem.path}`.substring(1),
            element: <Page />
          }
          routeArr.push(route)
        })
      })

      router.routes[1].children = routeArr

      console.log('---router---', router)
    } else {
      // menus不存在，说明退出了，所以要清空已经添加的路由
      router.routes[1].children = []
    }
  }, [userInfo])

  return (
    <Suspense
      fallback={
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
          }}
        >
          拼命加载中...
        </div>
      }
    >
      <RouterProvider router={router} />
    </Suspense>
  )
}

export default App
